﻿<template>
  <view class="message-center-container">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <text class="navbar-title">消息中心</text>
      <view class="navbar-actions">
        <view class="search-btn" @click="toggleSearch">
          <text class="icon">🔍</text>
          <text class="action-text">搜索匹配</text>
        </view>
        
        <view class="clear-btn" @click="showClearOptions">
          <text class="icon">🗑️</text>
          <text class="action-text">清除未读</text>
        </view>
      </view>
    </view>

    <!-- 功能按钮区 -->
    <view class="function-buttons">
      <view 
        v-for="button in functionButtons" 
        :key="button.type"
        class="function-button"
        :class="{ active: activeButton === button.type }"
        @click="switchFunction(button.type)"
      >
        <view class="button-icon">
          <text class="icon">{{ button.icon }}</text>
        </view>
        <text class="button-text">{{ button.text }}</text>
        <view v-if="button.badge > 0" class="button-badge">{{ button.badge }}</view>
      </view>
    </view>

    <!-- 消息列表 -->
    <scroll-view scroll-y class="conversation-list">
      <!-- 私信模块 -->
      <view v-if="activeButton === 'private'" class="message-group">
        <view class="group-header">
          <text class="group-date">私信列表</text>
        </view>
        
        <view 
          v-for="conversation in privateMessages" 
          :key="conversation.id"
          class="conversation-item"
          @click="enterPrivateChat(conversation)"
        >
          <image 
            :src="conversation.avatar || '/static/images/default-avatar.png'" 
            class="avatar"
            @error="handleImageError"
          ></image>
          
          <view class="conversation-content">
            <view class="conversation-header">
              <text class="nickname">{{ conversation.nickname || '未知用户' }}</text>
              <text class="time">{{ formatTime(conversation.time) }}</text>
            </view>
            
            <view class="message-preview">
              <text class="message-text" :class="{ 'read-message': conversation.unread === 0 }">{{ conversation.lastMessage || '暂无消息' }}</text>
              <view v-if="conversation.unread > 0" class="unread-badge">
                {{ conversation.unread }}
              </view>
            </view>
          </view>
        </view>
        
        <view v-if="privateMessages.length === 0" class="empty-state">
          <text>暂无私信消息</text>
        </view>
      </view>

      <!-- 互动消息模块 -->
      <view v-if="activeButton === 'interaction'" class="message-group">
        <view class="group-header">
          <text class="group-date">互动消息</text>
        </view>
        
        <view 
          v-for="interaction in interactionMessages" 
          :key="interaction.id"
          class="conversation-item"
          @click="viewInteraction(interaction)"
        >
          <image 
            :src="interaction.avatar || '/static/images/default-avatar.png'" 
            class="avatar"
            @error="handleImageError"
          ></image>
          
          <view class="conversation-content">
            <view class="conversation-header">
              <text class="nickname">{{ interaction.nickname || '未知用户' }}</text>
              <text class="time">{{ formatTime(interaction.time) }}</text>
            </view>
            
            <view class="message-preview">
              <text class="message-text" :class="{ 'read-message': interaction.unread === 0 }">{{ interaction.content || '暂无内容' }}</text>
              <view v-if="interaction.unread > 0" class="unread-badge">
                {{ interaction.unread }}
              </view>
            </view>
            
            <view class="interaction-type">
              <text>{{ getInteractionTypeText(interaction.type) }}</text>
            </view>
          </view>
        </view>
        
        <view v-if="interactionMessages.length === 0" class="empty-state">
          <text>暂无互动消息</text>
        </view>
      </view>
      
      <!-- 通知消息模块 -->
      <view v-if="activeButton === 'notification'" class="message-group">
        <view class="group-header">
          <text class="group-date">系统通知</text>
        </view>
        
        <view 
          v-for="notification in notificationMessages" 
          :key="notification.id"
          class="conversation-item"
          @click="viewNotification(notification)"
        >
          <image 
            :src="notification.avatar || '/static/images/default-avatar.png'" 
            class="avatar"
            @error="handleImageError"
          ></image>
          
          <view class="conversation-content">
            <view class="conversation-header">
              <text class="nickname">{{ notification.title || '系统通知' }}</text>
              <text class="time">{{ formatTime(notification.time) }}</text>
            </view>
            
            <view class="message-preview">
              <text class="message-text" :class="{ 'read-message': notification.unread === 0 }">{{ notification.content || '暂无内容' }}</text>
              <view v-if="notification.unread > 0" class="unread-badge">
                {{ notification.unread }}
              </view>
            </view>
          </view>
        </view>
        
        <view v-if="notificationMessages.length === 0" class="empty-state">
          <text>暂无通知消息</text>
        </view>
      </view>

      <!-- 推荐消息模块 -->
      <view v-if="activeButton === 'recommend'" class="message-group">
        <view class="group-header">
          <text class="group-date">推荐消息</text>
        </view>
        
        <view 
          v-for="recommend in recommendMessages" 
          :key="recommend.id"
          class="conversation-item"
          @click="viewRecommend(recommend)"
        >
          <image 
            :src="recommend.avatar || '/static/images/default-avatar.png'" 
            class="avatar"
            @error="handleImageError"
          ></image>
          
          <view class="conversation-content">
            <view class="conversation-header">
              <text class="nickname">{{ recommend.title || '推荐消息' }}</text>
              <text class="time">{{ formatTime(recommend.time) }}</text>
            </view>
            
            <view class="message-preview">
              <text class="message-text" :class="{ 'read-message': recommend.unread === 0 }">{{ recommend.content || '暂无内容' }}</text>
              <view v-if="recommend.unread > 0" class="unread-badge">
                {{ recommend.unread }}
              </view>
            </view>
            <!-- 推荐类型标签 -->
            <view v-if="recommend.type" class="recommend-type">
              <text>{{ getRecommendTypeText(recommend.type) }}</text>
            </view>
          </view>
        </view>
        
        <view v-if="recommendMessages.length === 0" class="empty-state">
          <text>暂无推荐消息</text>
        </view>
      </view>
    </scroll-view>
    
    <customTabBar />
  </view>
</template>

<script>
import customTabBar from '@/components/CustomTabBar.vue'

export default {
  components: {
    customTabBar
  },
  data() {
    return {
      activeButton: 'private',
      showSearchBar: false,
      isDestroyed: false, // 添加销毁标记
      
      // 消息数据
      privateMessages: [],
      
      interactionMessages: [],
      notificationMessages: [
        {
          id: 'nt1',
          avatar: '/static/images/default-avatar.png',
          title: '任务通知',
          content: '您的"代拿外卖"任务已被用户TestUser领取',
          time: Date.now() - 1000 * 60 * 10,
          unread: 1
        },
        {
          id: 'nt2',
          avatar: '/static/images/default-avatar.png',
          title: '系统通知',
          content: '您的账号信用分已更新，当前信用分：120',
          time: Date.now() - 1000 * 60 * 60 * 24,
          unread: 0
        }
      ],
      
      // 推荐消息初始数据
      recommendMessages: [
        {
          id: 'rc1',
          avatar: '/static/images/default-avatar.png',
          title: '任务推荐',
          content: '根据您的兴趣，推荐查看"校园跑腿"相关任务',
          time: Date.now() - 1000 * 60 * 60 * 2,
          unread: 1,
          type: 'task'
        }
      ],
      
      // 功能按钮配置
      functionButtons: [
        { type: 'private', icon: '💬', text: '私信', badge: 2 },
        { type: 'interaction', icon: '❤️', text: '互动', badge: 0 },
        { type: 'notification', icon: '🔔', text: '通知', badge: 1 },
        { type: 'recommend', icon: '⭐', text: '推荐', badge: 1 }
      ]
    }
  },
  onLoad() {
    console.log('=== MessageCenter 页面加载 ===')
    this.isDestroyed = false;
    console.log('onLoad: isDestroyed =', this.isDestroyed);
    this.loadPrivateMessages(); // 加载私信列表
    this.loadInteractionMessages();
    this.loadNotificationMessages();
    this.loadRecommendMessages(); // 加载推荐消息
  },
  onShow() {
    console.log('=== MessageCenter 页面显示 ===');
    console.log('onShow: isDestroyed =', this.isDestroyed);
    if (!this.isDestroyed) {
      console.log('onShow: 触发 loadInteractionMessages');
      this.loadPrivateMessages(); // 重新加载私信列表
      this.loadInteractionMessages();
      this.loadNotificationMessages();
      this.loadRecommendMessages(); // 重新加载推荐消息
    }
  },
  onUnload() {
    console.log('=== MessageCenter 页面卸载 ===');
    console.log('onUnload: 执行前 isDestroyed =', this.isDestroyed);
    this.isDestroyed = true;
    uni.$off('refreshMessages', this.handleRefreshMessages);
    console.log('onUnload: 执行后 isDestroyed =', this.isDestroyed);
  },
  methods: {
    // 测试手动加载互动消息
    testLoadInteraction() {
      console.log('=== 手动触发 testLoadInteraction ===');
      this.isDestroyed = false; // 强制设为未销毁
      this.loadInteractionMessages(); // 直接调用加载方法
    },
    
    // 检查数据库状态
    async checkDatabase() {
      try {
        console.log('=== 检查数据库状态 ===')
        const result = await uniCloud.callFunction({
          name: 'checkDatabase',
          data: {}
        })
        
        console.log('数据库检查结果:', result)
        
        if (result.result && result.result.code === 200) {
          // 修复：使用模板字符串拼接数据，避免语法错误
          const dataCount = result.result.data.totalCount || 0;
          const top5Data = JSON.stringify(result.result.data.top5Data || [], null, 2);
          uni.showModal({
            title: '数据库状态',
            content: `总数据量: ${dataCount} 条\n前5条数据:\n${top5Data}`,
            showCancel: false,
            confirmText: '确定',
            // 适配长内容滚动
            success: (res) => {
              if (res.confirm) {
                console.log('用户确认查看数据库状态');
              }
            }
          })
        } else {
          uni.showToast({
            title: '检查失败',
            icon: 'none',
            duration: 2000
          })
        }
      } catch (e) {
        console.error('检查数据库失败:', e)
        uni.showToast({
          title: '检查失败: ' + e.message,
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    // 处理刷新消息事件
    handleRefreshMessages() {
      console.log('=== 收到消息刷新事件 ===')
      if (!this.isDestroyed) {
        console.log('1. 组件未销毁，开始刷新互动消息...')
        this.loadInteractionMessages()
      } else {
        console.log('⚠️ 组件已销毁，跳过刷新')
      }
    },
    
    // 处理图片加载错误
    handleImageError(e) {
      console.log('图片加载失败:', e)
      e.target.src = '/static/images/default-avatar.png'
    },
    
    // 加载互动消息
    async loadInteractionMessages() {
      console.log('=== 加载互动消息 ===');
      if (this.isDestroyed) return;

      try {
        // 获取当前用户ID（用户B）
        const currentUserId = this.getCurrentUserId();
        if (!currentUserId) {
          console.log('❌ 用户未登录');
          return;
        }

        // 调用查询云函数
        const res = await uniCloud.callFunction({
          name: 'getInteractionMessages',
          data: { receiverId: currentUserId } // 关键：接收者ID为当前用户
        });

        if (res.result.success) {
          // 渲染互动消息
          this.interactionMessages = res.result.data.map(item => ({
            id: item._id,
            messageId: item._id, // 添加 messageId 字段
            type: item.type,
            avatar: item.sender_avatar,
            nickname: item.sender_nickname,
            content: item.content,
            time: item.create_time,
            unread: item.is_read ? 0 : 1,
            postId: item.post_id
          }));
          this.updateUnreadCounts(); // 更新未读徽章
        } else {
          this.interactionMessages = [];
          uni.showToast({ title: '加载互动消息失败', icon: 'none' });
        }
      } catch (e) {
        console.error('加载互动消息异常:', e);
        this.interactionMessages = [];
      }
    },
    
    // 加载私信列表
    async loadPrivateMessages() {
      console.log('=== 加载私信列表 ===');
      if (this.isDestroyed) return;

      try {
        // 获取当前用户ID
        const currentUserId = this.getCurrentUserId();
        if (!currentUserId) {
          console.log('❌ 用户未登录');
          return;
        }

        // 调用获取聊天列表云函数
        const res = await uniCloud.callFunction({
          name: 'getChatList',
          data: { userId: currentUserId }
        });

        if (res.result && res.result.code === 200) {
          console.log('📋 原始私信数据:', res.result.data);
          // 渲染私信列表
          this.privateMessages = res.result.data.map(item => {
            const mappedItem = {
              id: item.partnerId,
              avatar: item.partnerAvatar || '/static/images/default-avatar.png',
              nickname: item.partnerNickname || '未知用户',
              lastMessage: item.lastMessage || '暂无消息',
              time: item.lastMessageTime,
              unread: item.unread || 0,
              taskId: item.lastTaskId,
              lastMessageType: item.lastMessageType
            };
            console.log('📋 映射后的私信项:', mappedItem);
            return mappedItem;
          });
          this.updateUnreadCounts(); // 更新未读徽章
          console.log('✅ 私信列表加载成功:', this.privateMessages.length, '条');
        } else {
          this.privateMessages = [];
          console.log('❌ 私信列表加载失败:', res.result?.msg);
        }
      } catch (e) {
        console.error('加载私信列表异常:', e);
        this.privateMessages = [];
      }
    },
    
    // 加载模拟互动消息（保留，用于云函数异常时兜底）
    loadMockInteractionMessages() {
      console.log('=== 加载模拟互动消息 ===')
      this.interactionMessages = [
        {
          id: 'mock1',
          type: 'like',
          avatar: '/static/images/avatar4.png',
          nickname: '校园同学',
          content: '点赞了您的任务发布',
          time: Date.now() - 1000 * 60 * 60,
          unread: 1,
          postId: 'post123'
        }
      ]
      this.updateUnreadCounts()
      console.log('✅ 模拟互动消息加载完成')
    },

    // 加载通知消息
    async loadNotificationMessages() {
      console.log('=== 加载通知消息 ===');
      if (this.isDestroyed) return;

      try {
        const currentUserId = this.getCurrentUserId();
        if (!currentUserId) {
          console.log('❌ 用户未登录');
          return;
        }

        const res = await uniCloud.callFunction({
          name: 'getNotificationMessages',
          data: { 
            userId: currentUserId,
            limit: 50
          }
        });

        if (res.result.success) {
          this.notificationMessages = res.result.data.map(item => ({
            id: item._id,
            messageId: item._id,
            type: item.type,
            category: item.category,
            title: item.title,
            content: item.content,
            time: item.create_time,
            unread: item.is_read ? 0 : 1,
            priority: item.priority,
            actionUrl: item.action_url,
            actionText: item.action_text,
            relatedId: item.related_id,
            relatedType: item.related_type
          }));
          this.updateUnreadCounts();
        } else {
          this.notificationMessages = [];
          uni.showToast({ title: '加载通知消息失败', icon: 'none' });
        }
      } catch (e) {
        console.error('加载通知消息异常:', e);
        this.notificationMessages = [];
      }
    },

    // 加载推荐消息
    async loadRecommendMessages() {
      console.log('=== 加载推荐消息 ===');
      if (this.isDestroyed) return;

      try {
        const currentUserId = this.getCurrentUserId();
        if (!currentUserId) {
          console.log('❌ 用户未登录');
          return;
        }

        const res = await uniCloud.callFunction({
          name: 'getRecommendMessages',
          data: { 
            userId: currentUserId,
            limit: 10
          }
        });

        if (res.result.code === 200) {
          this.recommendMessages = res.result.data.map(item => ({
            id: item._id,
            messageId: item._id,
            type: item.type,
            title: item.title,
            content: item.content,
            time: item.create_time || item.createTime, // 优先使用 create_time
            unread: item.is_read ? 0 : 1,
            reason: item.reason,
            score: item.score,
            taskId: item.task_id,
            activityId: item.activity_id,
            targetUserId: item.target_user_id,
            avatar: item.avatar || '/static/images/default-avatar.png' // 确保有头像
          }));
          this.updateUnreadCounts();
          console.log('✅ 推荐消息加载完成，共', this.recommendMessages.length, '条');
        } else {
          this.recommendMessages = [];
          console.log('❌ 推荐消息加载失败:', res.result.msg);
        }
      } catch (e) {
        console.error('加载推荐消息异常:', e);
        this.recommendMessages = [];
      }
    },

    // 更新未读计数
    updateUnreadCounts() {
      if (this.isDestroyed) return
      
      console.log('=== 更新未读计数 ===')
      const privateUnread = this.privateMessages.filter(m => m.unread > 0).length
      const interactionUnread = this.interactionMessages.filter(m => m.unread > 0).length
      const notificationUnread = this.notificationMessages.filter(m => m.unread > 0).length
      const recommendUnread = this.recommendMessages.filter(m => m.unread > 0).length
      
      console.log('未读计数:', {
        private: privateUnread,
        interaction: interactionUnread,
        notification: notificationUnread,
        recommend: recommendUnread
      })
      
      this.functionButtons[0].badge = privateUnread
      this.functionButtons[1].badge = interactionUnread
      this.functionButtons[2].badge = notificationUnread
      this.functionButtons[3].badge = recommendUnread
      
      console.log('✅ 未读计数更新完成')
    },
    
    // 获取当前用户ID
    getCurrentUserId() {
      try {
        let userInfo = uni.getStorageSync('uni-id-pages-userInfo')
        if (typeof userInfo === 'string') {
          userInfo = JSON.parse(userInfo)
        }
        return userInfo && userInfo._id ? userInfo._id : ''
      } catch (e) {
        console.error('获取用户ID失败:', e)
        return ''
      }
    },
    
    // 切换功能按钮
    switchFunction(type) {
      console.log('=== switchFunction 被调用 ===');
      console.log('switchFunction: 传入的 type =', type);
      if (this.isDestroyed) {
        console.log('switchFunction: 组件已销毁，跳过');
        return
      }
      console.log('switchFunction: 切换前 activeButton =', this.activeButton);
      this.activeButton = type;
      console.log('switchFunction: 切换后 activeButton =', this.activeButton);
      if (type === 'interaction') {
        console.log('switchFunction: 触发 loadInteractionMessages');
        this.loadInteractionMessages()
      }
    },
    
    // 切换搜索栏
    toggleSearch() {
      if (this.isDestroyed) return
      this.showSearchBar = !this.showSearchBar
    },
    
    // 显示统计
    showStats() {
      if (this.isDestroyed) return
      uni.showToast({
        title: '统计功能开发中',
        icon: 'none'
      })
    },
    
    // 显示清除选项
    showClearOptions() {
      if (this.isDestroyed) return
      
      uni.showActionSheet({
        itemList: [
          '清除所有未读',
          '清除私信未读',
          '清除互动未读',
          '清除通知未读',
          '清除推荐未读'
        ],
        success: async (res) => {
          const index = res.tapIndex;
          switch (index) {
            case 0:
              await this.clearUnread('all');
              break;
            case 1:
              await this.clearUnread('private');
              break;
            case 2:
              await this.clearUnread('interaction');
              break;
            case 3:
              await this.clearUnread('notification');
              break;
            case 4:
              await this.clearUnread('recommend');
              break;
          }
        }
      });
    },

    // 清除未读（支持按类型）
    async clearUnread(messageType = 'all') {
      if (this.isDestroyed) return
      
      const typeNames = {
        'all': '所有',
        'private': '私信',
        'interaction': '互动',
        'notification': '通知',
        'recommend': '推荐'
      };
      
      const typeName = typeNames[messageType] || '所有';
      
      // 新增二次确认
      uni.showModal({
        title: '确认清除',
        content: `是否清空${typeName}未读消息标记？`,
        success: async (res) => {
          if (res.confirm) {
            // 调用云函数批量标记已读
            await this.markAllMessagesAsRead(messageType === 'all' ? null : messageType);
          }
        }
      })
    },
    
    // 时间格式化
    formatTime(time) {
      if (!time) return ''
      try {
        let date
        // 处理不同的时间格式
        if (typeof time === 'number') {
          // Unix时间戳（毫秒）
          date = new Date(time)
        } else if (typeof time === 'string') {
          // 字符串格式
          date = new Date(time)
        } else if (time instanceof Date) {
          // Date对象
          date = time
        } else {
          return ''
        }
        
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          return ''
        }
        
        const now = new Date()
        const diff = now - date
        
        if (diff < 60 * 1000) return '刚刚'
        if (diff < 60 * 60 * 1000) return Math.floor(diff / 60000) + '分钟前'
        if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
          return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
        }
        return `${date.getMonth() + 1}-${date.getDate()}`
      } catch (e) {
        console.error('时间格式化失败:', e)
        return ''
      }
    },
    
    // 获取互动类型文本
    getInteractionTypeText(type) {
      const typeMap = {
        'like': '点赞',
        'comment': '评论'
      }
      return typeMap[type] || '互动'
    },
    
    // 获取推荐类型文本
    getRecommendTypeText(type) {
      const typeMap = {
        'task': '任务推荐',
        'activity': '系统活动',
        'hot': '热门推荐',
        'personalized': '个性化推荐',
        'system': '系统推荐'
      }
      return typeMap[type] || '推荐'
    },
    
    // 进入私信聊天
    async enterPrivateChat(conversation) {
      if (this.isDestroyed || !conversation) return
      
      console.log('🔍 进入私信 - 完整conversation对象:', conversation);
      console.log('🔍 conversation.id:', conversation.id);
      console.log('🔍 conversation.nickname:', conversation.nickname);
      console.log('🔍 conversation.avatar:', conversation.avatar);
      
      // 标记为已读（前端）
      conversation.unread = 0
      this.updateUnreadCounts()
      
      // 调用云函数标记聊天消息为已读
      if (conversation.id) {
        try {
          await this.markChatMessageAsRead(conversation.id);
        } catch (e) {
          console.error('标记聊天消息已读失败:', e);
        }
      }
      
      // 构建跳转URL
      let url = '/pages/message/Chat/Chat'
      const params = []
      
      // 如果有任务ID，添加任务相关参数
      if (conversation.taskId) {
        params.push(`taskId=${conversation.taskId}`)
      }
      
      // 添加聊天对象ID
      params.push(`partnerId=${conversation.id}`)
      
      // 添加聊天对象头像和昵称
      if (conversation.avatar) {
        params.push(`partnerAvatar=${encodeURIComponent(conversation.avatar)}`)
      }
      if (conversation.nickname) {
        params.push(`partnerNickname=${encodeURIComponent(conversation.nickname)}`)
      }
      
      // 如果有参数，添加到URL
      if (params.length > 0) {
        url += '?' + params.join('&')
      }
      
      console.log('跳转到聊天页面:', url)
      console.log('传递的聊天对象信息:', { 
        id: conversation.id, 
        nickname: conversation.nickname, 
        avatar: conversation.avatar 
      })
      
      // 跳转到聊天页面
      uni.navigateTo({
        url: url,
        fail: (err) => {
          console.error('跳转聊天页面失败:', err)
          uni.showToast({
            title: '跳转失败',
            icon: 'none'
          })
        }
      })
    },
       
    
    // 获取推荐类型分布
    getRecommendTypeDistribution(data) {
      const typeCount = {};
      data.forEach(item => {
        typeCount[item.type] = (typeCount[item.type] || 0) + 1;
      });
      
      return Object.entries(typeCount)
        .map(([type, count]) => `${type}: ${count}条`)
        .join('\n');
    },
    // 查看互动消息
    async viewInteraction(interaction) {
      if (this.isDestroyed || !interaction) return
      
      console.log('查看互动:', interaction.id)
      
      // 标记为已读
      interaction.unread = 0
      this.updateUnreadCounts()
      
      // 调用云函数标记消息为已读
      if (interaction.messageId) {
        await this.markMessageAsRead(interaction.messageId)
      }
      
      if (interaction.postId) {
        uni.navigateTo({
          url: `/pages/circle/post-datail/post-datail?id=${interaction.postId}`
        })
      } else {
        uni.showToast({
          title: '帖子ID不存在',
          icon: 'none'
        })
      }
    },
    
    // 查看通知消息
    viewRecommend(recommend) {
      if (this.isDestroyed || !recommend) return
      
      console.log('查看推荐:', recommend.id)
      
      // 标记为已读
      recommend.unread = 0
      this.updateUnreadCounts()
      
      // 调用云函数标记消息为已读（如果有messageId）
      if (recommend.messageId) {
        this.markMessageAsRead(recommend.messageId).catch(err => {
          console.log('标记推荐消息为已读失败:', err);
        });
      }
      
      // 根据推荐类型跳转到不同页面
      if (recommend.type === 'task' && recommend.taskId) {
        // 任务推荐跳转到任务详情
        uni.navigateTo({
          url: `/pages/task/TaskDetail/TaskDetail?id=${recommend.taskId}`
        });
      } else if (recommend.type === 'personalized' && recommend.taskId) {
        // 个性化任务推荐跳转到任务详情
        uni.navigateTo({
          url: `/pages/task/TaskDetail/TaskDetail?id=${recommend.taskId}`
        });
      } else if (recommend.type === 'hot' && recommend.taskId) {
        // 热门任务推荐跳转到任务详情
        uni.navigateTo({
          url: `/pages/task/TaskDetail/TaskDetail?id=${recommend.taskId}`
        });
      } else if (recommend.type === 'activity') {
        // 活动推荐跳转到首页
        uni.switchTab({
          url: '/pages/index/index'
        });
      } else {
        // 其他推荐跳转到首页
        uni.switchTab({
          url: '/pages/index/index'
        });
      }
    },

    // 查看通知消息
    viewNotification(notification) {
      if (this.isDestroyed || !notification) return
      
      console.log('查看通知:', notification.id)
      
      // 标记为已读
      notification.unread = 0
      this.updateUnreadCounts()
      
      // 调用云函数标记消息为已读（如果有messageId）
      if (notification.messageId) {
        this.markMessageAsRead(notification.messageId).catch(err => {
          console.log('标记通知消息为已读失败:', err);
        });
      }
      
      // 根据通知类型跳转到不同页面
      if (notification.actionUrl) {
        // 如果有指定的跳转链接，直接跳转
        uni.navigateTo({
          url: notification.actionUrl
        });
      } else if (notification.relatedType === 'task' && notification.relatedId) {
        // 任务相关通知跳转到任务详情
        uni.navigateTo({
          url: `/pages/task/TaskDetail/TaskDetail?id=${notification.relatedId}`
        });
      } else {
        // 其他通知跳转到首页
        uni.switchTab({
          url: '/pages/index/index'
        });
      }
    },

    // 标记消息为已读
    async markMessageAsRead(messageId) {
      if (!messageId || this.isDestroyed) return
      
      try {
        console.log('标记消息为已读:', messageId)
        
        // 判断是否为推荐消息（推荐消息ID通常以特定前缀开头）
        const isRecommendMessage = messageId.startsWith('personalized_') || 
                                  messageId.startsWith('hot_') || 
                                  messageId.startsWith('system_') ||
                                  messageId.startsWith('fallback_') ||
                                  messageId.startsWith('error_');
        
        let result
        if (isRecommendMessage) {
          // 调用推荐消息标记已读云函数
          result = await uniCloud.callFunction({
            name: 'markRecommendMessageRead',
            data: {
              messageId: messageId,
              userId: this.getCurrentUserId()
            }
          })
        } else {
          // 调用普通消息标记已读云函数
          result = await uniCloud.callFunction({
            name: 'markMessageRead',
            data: {
              messageId: messageId,
              userId: this.getCurrentUserId()
            }
          })
        }
        
        if (result.result && result.result.code === 200) {
          console.log('✅ 消息标记为已读成功')
        } else {
          console.log('❌ 标记消息失败:', result.result)
        }
      } catch (e) {
        console.error('❌ 标记消息异常:', e)
      }
    },

    // 标记通知为已读
    async markNotificationAsRead(notificationId) {
      if (!notificationId || this.isDestroyed) return
      
      try {
        console.log('标记通知为已读:', notificationId)
        const result = await uniCloud.callFunction({
          name: 'markNotificationRead',
          data: {
            notificationId: notificationId,
            userId: this.getCurrentUserId()
          }
        })
        
        if (result.result && result.result.success) {
          console.log('✅ 通知标记为已读成功')
        } else {
          console.log('❌ 标记通知失败:', result.result)
        }
      } catch (e) {
        console.error('❌ 标记通知异常:', e)
      }
    },

    // 标记聊天消息为已读
    async markChatMessageAsRead(partnerId) {
      if (!partnerId || this.isDestroyed) return
      
      try {
        const currentUserId = this.getCurrentUserId()
        console.log('标记聊天消息为已读:', { partnerId, currentUserId })
        
        if (!currentUserId) {
          console.log('❌ 无法获取当前用户ID')
          return
        }
        
        const result = await uniCloud.callFunction({
          name: 'markChatMessageRead',
          data: {
            partnerId: partnerId,
            userId: currentUserId
          }
        })
        
        console.log('markChatMessageRead 结果:', result)
        
        if (result.result && result.result.code === 200) {
          console.log('✅ 聊天消息标记为已读成功，更新了', result.result.data.updatedCount, '条消息')
        } else {
          console.log('❌ 标记聊天消息失败:', result.result)
          // 不显示错误提示，因为可能是没有未读消息
        }
      } catch (e) {
        console.error('❌ 标记聊天消息异常:', e)
      }
    },

    // 批量标记所有消息为已读
    async markAllMessagesAsRead(messageType = null) {
      if (this.isDestroyed) return
      
      try {
        const currentUserId = this.getCurrentUserId();
        console.log('批量标记消息为已读，类型:', messageType || 'all')
        console.log('当前用户ID:', currentUserId)
        
        const result = await uniCloud.callFunction({
          name: 'markAllMessagesRead',
          data: {
            userId: currentUserId,
            messageType: messageType
          }
        })
        
        console.log('云函数返回结果:', result)
        
        if (result.result && result.result.code === 200) {
          console.log('✅ 批量标记已读成功，更新了', result.result.data.updatedCount, '条消息')
          
          // 重新加载消息列表以同步状态
          console.log('开始重新加载消息列表...')
          await Promise.all([
            this.loadPrivateMessages(),
            this.loadInteractionMessages(),
            this.loadNotificationMessages(),
            this.loadRecommendMessages()
          ]);
          
          console.log('消息列表重新加载完成')
          
          uni.showToast({
            title: `已标记${result.result.data.updatedCount}条消息为已读`,
            icon: 'success'
          });
        } else {
          console.log('❌ 批量标记已读失败:', result.result)
          uni.showToast({
            title: '标记已读失败',
            icon: 'none'
          });
        }
      } catch (e) {
        console.error('❌ 批量标记已读异常:', e)
        uni.showToast({
          title: '标记已读失败',
          icon: 'none'
        });
      }
    },

    // 清理测试数据
    async clearTestData() {
      try {
        console.log('=== 清理测试数据 ===')
        console.log('1. 调用 clearTestData 云函数，当前用户ID:', this.getCurrentUserId())
        
        // 调用云函数时添加日志，确认参数是否正确
        const result = await uniCloud.callFunction({
          name: 'clearTestData',
          data: {
            userId: this.getCurrentUserId()
          }
        })
        
        console.log('2. clearTestData 云函数返回结果:', result) // 关键日志：打印完整返回结果
        console.log('2.1 结果中的 result 字段:', result.result) // 打印云函数业务返回
        console.log('2.2 结果中的 errCode:', result.errCode) // 打印错误码（若有）
        
        if (this.isDestroyed) {
          console.log('⚠️ 组件已销毁，跳过清理后逻辑')
          return
        }
        
        if (result.success && result.result && result.result.code === 200) {
          // 处理可能的 undefined 数据
          const deletedCount = result.result.data?.deletedCount || 0;
          const remainingCount = result.result.data?.remainingCount || 0;
          console.log('3. 清理成功：删除', deletedCount, '条，剩余', remainingCount, '条')
          
          uni.showModal({
            title: '清理完成',
            content: `删除了 ${deletedCount} 条测试数据\n剩余 ${remainingCount} 条真实数据`,
            showCancel: false,
            success: () => {
              console.log('4. 用户确认后重新加载互动消息')
              this.loadInteractionMessages()
            }
          })
        } else {
          console.log('❌ 清理失败：云函数返回非200状态', {
            success: result.success,
            errCode: result.errCode,
            errMsg: result.errMsg,
            result: result.result
          })
          uni.showToast({
            title: `清理失败: ${result.errMsg || '未知错误'}`,
            icon: 'none',
            duration: 3000
          })
        }
      } catch (e) {
        console.error('❌ 清理测试数据异常（try-catch捕获）:', {
          message: e.message,
          stack: e.stack,
          name: e.name
        })
        uni.showToast({
          title: '清理失败: ' + e.message,
          icon: 'none',
          duration: 3000
        })
      }
    },

    // 测试完整互动流程
    async testInteractionFlow() {
      try {
        console.log('=== 开始测试完整互动流程 ===');
        
        const currentUserId = this.getCurrentUserId();
        if (!currentUserId) {
          uni.showToast({ title: '请先登录', icon: 'none' });
          return;
        }
        
        // 使用测试数据
        const testData = {
          userId: currentUserId, // 当前用户作为点赞者
          postId: 'test_post_123', // 测试帖子ID
          postTitle: '测试帖子标题',
          receiverId: '68c3dd9a89bd271718b9b80c' // 另一个用户ID作为接收者
        };
        
        console.log('测试参数:', testData);
        
        const result = await uniCloud.callFunction({
          name: 'testInteractionFlow',
          data: testData
        });
        
        console.log('测试结果:', result);
        
        if (result.result && result.result.code === 200) {
          const data = result.result.data;
          uni.showModal({
            title: '测试结果',
            content: `点赞记录: ${data.summary.likeCount} 条\n互动消息: ${data.summary.messageCount} 条\n\n详细结果请查看控制台`,
            showCancel: false,
            success: () => {
              // 重新加载互动消息
              this.loadInteractionMessages();
            }
          });
        } else {
          uni.showToast({
            title: '测试失败: ' + (result.result?.msg || '未知错误'),
            icon: 'none',
            duration: 3000
          });
        }
      } catch (e) {
        console.error(' 测试流程异常:', e);
        uni.showToast({
          title: '测试异常: ' + e.message,
          icon: 'none',
          duration: 3000
        });
      }
    },

    // 测试用户信息查询
    async testUserQuery() {
      try {
        console.log('=== 开始测试用户信息查询 ===');
        
        const currentUserId = this.getCurrentUserId();
        if (!currentUserId) {
          uni.showToast({ title: '请先登录', icon: 'none' });
          return;
        }
        
        console.log('测试用户ID:', currentUserId);
        
        const result = await uniCloud.callFunction({
          name: 'testUserQuery',
          data: {
            userId: currentUserId
          }
        });
        
        console.log('用户查询结果:', result);
        
        if (result.result && result.result.code === 200) {
          const data = result.result.data;
          uni.showModal({
            title: '用户信息查询结果',
            content: `用户ID: ${data.userId}\n昵称: ${data.nickname || '未设置'}\n头像: ${data.avatar}\n\n详细数据请查看控制台`,
            showCancel: false,
            success: () => {
              console.log('完整用户数据:', data.rawData);
            }
          });
        } else {
          uni.showToast({
            title: '查询失败: ' + (result.result?.msg || '未知错误'),
            icon: 'none',
            duration: 3000
          });
        }
      } catch (e) {
        console.error(' 测试用户查询异常:', e);
        uni.showToast({
          title: '测试异常: ' + e.message,
          icon: 'none',
          duration: 3000
        });
      }
    },

    // 测试点赞流程
    async testLikeFlow() {
      try {
        console.log('=== 开始测试点赞流程 ===');
        
        const currentUserId = this.getCurrentUserId();
        if (!currentUserId) {
          uni.showToast({ title: '请先登录', icon: 'none' });
          return;
        }
        
        // 使用测试数据
        const testData = {
          userId: currentUserId,
          postId: 'test_post_' + Date.now(),
          receiverId: '68c3dd9a89bd271718b9b80c', // 另一个用户ID
          postTitle: '测试帖子标题'
        };
        
        console.log('测试参数:', testData);
        
        const result = await uniCloud.callFunction({
          name: 'testLikeFlow',
          data: testData
        });
        
        console.log('测试结果:', result);
        
        if (result.result && result.result.code === 200) {
          const data = result.result.data;
          uni.showModal({
            title: '测试成功',
            content: `用户: ${data.nickname}\n消息ID: ${data.messageId}\n\n详细结果请查看控制台`,
            showCancel: false,
            success: () => {
              // 重新加载互动消息
              this.loadInteractionMessages();
            }
          });
        } else {
          uni.showToast({
            title: '测试失败: ' + (result.result?.msg || '未知错误'),
            icon: 'none',
            duration: 3000
          });
        }
      } catch (e) {
        console.error(' 测试点赞流程异常:', e);
        uni.showToast({
          title: '测试异常: ' + e.message,
          icon: 'none',
          duration: 3000
        });
      }
    },

    // 测试自点赞逻辑
    async testSelfLike() {
      try {
        console.log('=== 开始测试自点赞逻辑 ===');
        
        const currentUserId = this.getCurrentUserId();
        if (!currentUserId) {
          uni.showToast({ title: '请先登录', icon: 'none' });
          return;
        }
        
        // 使用测试数据（自点赞场景）
        const testData = {
          userId: currentUserId,
          postId: 'test_self_post_' + Date.now(),
          postTitle: '测试自点赞帖子'
        };
        
        console.log('测试参数:', testData);
        
        const result = await uniCloud.callFunction({
          name: 'testSelfLike',
          data: testData
        });
        
        console.log('测试结果:', result);
        
        if (result.result && result.result.code === 200) {
          const data = result.result.data;
          if (data.skipMessage) {
            uni.showModal({
              title: '自点赞测试成功',
              content: ` 自点赞逻辑正常工作\n\n用户: ${data.userId}\n帖子: ${data.postId}\n跳过消息生成: ${data.skipMessage}\n\n说明: 自己给自己的帖子点赞不会生成互动消息`,
              showCancel: false,
              success: () => {
                console.log('自点赞逻辑测试成功');
              }
            });
          } else {
            uni.showModal({
              title: '自点赞测试异常',
              content: ` 自点赞逻辑可能有问题\n\n用户: ${data.userId}\n帖子: ${data.postId}\n跳过消息生成: ${data.skipMessage}\n\n说明: 自点赞应该跳过消息生成`,
              showCancel: false
            });
          }
        } else {
          uni.showToast({
            title: '测试失败: ' + (result.result?.msg || '未知错误'),
            icon: 'none',
            duration: 3000
          });
        }
      } catch (e) {
        console.error(' 测试自点赞逻辑异常:', e);
        uni.showToast({
          title: '测试异常: ' + e.message,
          icon: 'none',
          duration: 3000
        });
      }
    },

    // 快速测试方法
    async quickTest() {
      try {
        console.log('=== 开始快速测试 ===')
        const result = await uniCloud.callFunction({
          name: 'quickTest',
          data: {
            userId: this.getCurrentUserId()
          }
        })
        
        console.log('快速测试结果:', result)
        
        if (result.result && result.result.code === 200) {
          console.log('✅ 测试数据插入成功，共', result.result.data.totalMessages, '条消息')
          
          // 延迟1秒后重新加载消息
          setTimeout(() => {
            console.log('重新加载互动消息...')
            this.loadInteractionMessages()
          }, 1000)
        } else {
          console.log('❌ 测试失败:', result.result)
        }
      } catch (e) {
        console.error('❌ 快速测试异常:', e)
      }
    },

    // 生成模拟推荐消息（临时方案）
    generateMockRecommendations() {
      const mockRecommendations = [
        {
          id: 'mock_personalized_1',
          type: 'task',
          title: '个性化任务推荐',
          content: '根据您的兴趣偏好，推荐"代拿外卖"任务（express类型，悬赏15元）',
          time: Date.now() - 1000 * 60 * 30,
          unread: 1,
          reason: '基于您对express类型任务的偏好',
          score: 0.8,
          taskId: 'mock_task_1'
        },
        {
          id: 'mock_hot_1',
          type: 'task',
          title: '热门任务推荐',
          content: '🔥 热门任务"校园跑腿"，悬赏25元，express类型',
          time: Date.now() - 1000 * 60 * 60,
          unread: 1,
          reason: '高悬赏金额，近期发布',
          score: 0.9,
          taskId: 'mock_task_2'
        },
        {
          id: 'mock_activity_1',
          type: 'activity',
          title: '系统活动推荐',
          content: '🎉 新手福利：完成前3个任务可获得额外50积分奖励！',
          time: Date.now() - 1000 * 60 * 60 * 3,
          unread: 1,
          reason: '新手用户专属福利',
          score: 0.9,
          activityId: 'mock_activity_1'
        }
      ];
      
      this.recommendMessages = mockRecommendations;
      this.updateUnreadCounts();
      console.log('✅ 模拟推荐消息生成完成，共', mockRecommendations.length, '条');
    }
  }
}
</script>

<style scoped>
.message-center-container {
  min-height: 100vh;
  background: #f6f8fc;
  display: flex;
  flex-direction: column;
}

.navbar {
  height: 110rpx;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  border-bottom: 1rpx solid #e0e6f1;
  box-shadow: 0 2rpx 8rpx rgba(160,180,220,0.08);
  overflow-x: auto;
  scrollbar-width: none;
  -webkit-overflow-scrolling: touch;
}

.navbar::-webkit-scrollbar {
  display: none;
}

.navbar-title {
  font-size: 38rpx;
  font-weight: bold;
  color: #333;
  letter-spacing: 2rpx;
  white-space: nowrap;
}

.navbar-actions {
  display: flex;
  align-items: center;
  gap: 16rpx;
  white-space: nowrap;
}

/* 统一导航栏按钮样式，新增 test-recommend-btn 样式 */
.search-btn, .stats-btn, .clear-btn, .clear-test-btn, .check-btn, .test-btn, .test-flow-btn, .test-user-btn, .test-self-btn, .test-recommend-btn {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 6rpx 10rpx;
  border-radius: 8rpx;
  transition: background 0.2s;
  white-space: nowrap;
}

.search-btn:active, .stats-btn:active, .clear-btn:active, .clear-test-btn:active, .check-btn:active, .test-btn:active, .test-flow-btn:active, .test-self-btn:active, .test-recommend-btn:active {
  background: #f0f0f0;
}

.action-text {
  font-size: 24rpx;
  color: #666;
}

.icon {
  font-size: 20rpx;
}

/* 功能按钮区 */
.function-buttons {
  width: 100%;
  background: #fff;
  padding: 18rpx 0 8rpx 0;
  box-shadow: 0 2rpx 8rpx rgba(160,180,220,0.04);
  display: flex;
  justify-content: space-around;
}

.function-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 120rpx;
  position: relative;
  cursor: pointer;
  border-radius: 20rpx;
  transition: all 0.3s ease;
  padding: 10rpx;
}

.function-button.active {
  background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
  transform: translateY(-2rpx);
}

.button-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background: #f6f8fc;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8rpx;
  box-shadow: 0 2rpx 8rpx #e6f7ff80;
  transition: all 0.3s ease;
}

.function-button.active .button-icon {
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  box-shadow: 0 4rpx 12rpx rgba(24, 144, 255, 0.3);
}

.button-text {
  font-size: 26rpx;
  color: #333;
  margin-top: 2rpx;
}

.button-badge {
  position: absolute;
  top: 10rpx;
  right: 22rpx;
  min-width: 28rpx;
  height: 28rpx;
  background: #ff3b30;
  color: #fff;
  font-size: 20rpx;
  border-radius: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8rpx;
  box-shadow: 0 2rpx 8rpx #ff3b30a0;
  font-weight: bold;
  z-index: 2;
}

/* 消息列表区 */
.conversation-list {
  flex: 1;
  background: #f6f8fc;
  padding: 0 0 20rpx 0;
}

.message-group {
  margin: 24rpx 0 0 0;
}

.group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 0 12rpx 32rpx;
}

.group-date {
  font-size: 26rpx;
  color: #8a99b3;
  font-weight: 500;
}

/* 消息项 */
.conversation-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin: 0 24rpx 18rpx 24rpx;
  background: #fff;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 24rpx rgba(160,180,220,0.10);
  min-height: 110rpx;
  padding: 0 24rpx;
  position: relative;
  transition: all 0.3s ease;
}

.conversation-item:active {
  transform: translateY(-2rpx);
  box-shadow: 0 6rpx 30rpx rgba(58,141,255,0.15);
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #e9f0fb;
  border: 2rpx solid #e0e6f1;
  object-fit: cover;
  margin-right: 20rpx;
}

.conversation-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.conversation-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.nickname {
  font-size: 32rpx;
  color: #222;
  font-weight: 500;
  margin-right: 12rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.time {
  font-size: 24rpx;
  color: #bbb;
  margin-left: 12rpx;
  white-space: nowrap;
}

.message-preview {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 8rpx;
}

.message-text {
  font-size: 26rpx;
  color: #8a99b3;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  transition: all 0.3s ease;
}

.read-message {
  color: #bbb !important;
  opacity: 0.7;
}

.unread-badge {
  min-width: 36rpx;
  height: 36rpx;
  background: #ff3b30;
  color: #fff;
  font-size: 22rpx;
  border-radius: 36rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 10rpx;
  margin-left: 12rpx;
  box-shadow: 0 2rpx 8rpx #ff3b30a0;
  font-weight: bold;
}

.interaction-type {
  margin-top: 6rpx;
  font-size: 22rpx;
  color: #1890ff;
  background: #e6f7ff;
  border-radius: 8rpx;
  padding: 2rpx 12rpx;
  display: inline-block;
}

/* 推荐类型标签样式 */
.recommend-type {
  margin-top: 6rpx;
  font-size: 22rpx;
  color: #722ed1;
  background: #f9f0ff;
  border-radius: 8rpx;
  padding: 2rpx 12rpx;
  display: inline-block;
}

.empty-state {
  height: 300rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #bbb;
  font-size: 30rpx;
  gap: 16rpx;
}
</style>
